<?php
require_once APPLICATION_PATH.'/controllers/AbstractBaseController.class.php';

class StoresController extends AbstractBaseController
{
	private $stores = array();

	public function init()
	{
		$storesJSON = file_get_contents('http://api.talis.com/stores?output=json');

		if ($storesJSON === FALSE)
		{
			throw new Zend_Exception('Cannot get list of stores');
		}

		$arrStores = json_decode($storesJSON, true);

		$this->stores = array();
		$arrStoreNames = $arrStores['http://api.talis.com/stores']['http://schemas.talis.com/2006/bigfoot/configuration#store'];
		foreach ($arrStoreNames as $storeName)
		{
			$storeUri = $storeName['value'];
			$shortName = substr($storeUri, strrpos($storeUri, '/')+1);
				
			$this->stores[] = $shortName;
		}

		sort($this->stores);
	}

	public function listAction()
	{
		$this->view->pageHeader = 'Stores';
		$this->view->stores = $this->stores;
	}
	
	public function jsonAction()
	{
		$this->disableLayout();
		
		$term = $this->getRequest()->getParam('term');
		
		$stores = array();
		foreach ($this->stores as $store)
		{
			if (strpos($store, $term) !== FALSE)
			{
				$stores[] = $store;
			}
		}
		
		echo json_encode($stores);
	}
	
}
?>